package com.jk1.bianligou.blg.aop;

import com.jk1.bianligou.blg.common.ErrorCode;
import com.jk1.bianligou.blg.domain.po.User;
import com.jk1.bianligou.blg.exception.BizException;
import com.jk1.bianligou.blg.service.UserService;
import com.jk1.bianligou.blg.utils.UserUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 商家权限校验切面
 * @author WHH
 */
@Aspect
@Component
public class MerchantCheckAspect {

    @Resource
    private UserService userService;

    // 定义切点为所有标注@MerchantCheck的方法
    @Pointcut("@annotation(com.jk1.bianligou.blg.aop.MerchantCheck)")
    public void merchantCheckPointcut() {}

    @Before("merchantCheckPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // 获取当前登录用户ID
        Long userId = UserUtils.getLoginUserId(request);
        // 查询用户信息
        User user = userService.getById(userId);
        // 校验用户类型
        if (user == null || user.getType() != 2) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "不是商家不允许访问！");
        }
    }
}